<template>
  <div id="student">
    <el-row class="padding-50">
      <el-col :span="24">
        <ul class="list">
          <li class="logo">
            <i class="iconfont icon-kaoshi"></i>
            <span>DORO-Learning-Online</span>
          </li>
          <li><router-link :to="`/student/learn/${courseId}`">章节学习</router-link></li>
          <li><router-link :to="`/student/learn_document/${courseId}`">课程资料</router-link></li>
          <li><router-link :to="`/student/learn_info/${courseId}`">课程信息</router-link></li>
          <li class="logo">智能学习助手</li>
          <li><router-link to="/student/message">我的消息</router-link></li>
          <li><router-link to="/student">返回首页</router-link></li>
          <li class="right" @mouseenter="flag = true" @mouseleave="flag = false">
            <a href="javascript:;">
              <i class="iconfont icon-Userselect icon"></i>{{ user.userName }}
            </a>
            <div class="msg" v-if="flag">
              <p @click="manage">管理中心</p>
              <p class="exit" @click="exit">退出</p>
            </div>
          </li>
        </ul>
      </el-col>
    </el-row>

    <div class="main">
      <h2>智能学习助手</h2>
      <div class="chat-container">
        <div class="chat-sidebar">
          <el-button type="primary" @click="startNewChat" icon="el-icon-plus">新对话</el-button>
          <ul class="chat-history">
            <li
              v-for="chat in chatList"
              :key="chat.chatID"
              :class="{ active: chat.chatID === currentChatId }"
              @click="loadChat(chat.chatID)"
            >
              {{ chat.content.slice(0, 12) }}{{ chat.content.length > 12 ? '...' : '' }}
              <i class="el-icon-delete" @click.stop="deleteChat(chat.chatID)"></i>
            </li>
          </ul>
        </div>

        <div class="chat-main">
          <div class="chat-log" v-if="chatLog.length">
            <div
              v-for="(msg, index) in chatLog"
              :key="index"
              :class="msg.speaker === 1 ? 'chat-user' : 'chat-ai'"
            >
              <span class="chat-content">{{ msg.content }}</span>
            </div>
          </div>
          <div v-else class="chat-empty">请开始新的对话或选择左侧历史记录</div>

          <div class="chat-input">
            <el-input
              v-model="inputContent"
              placeholder="请输入问题"
              @keyup.enter="sendMessage"
              clearable
            />
            <el-button type="primary" @click="sendMessage" :loading="sending">发送</el-button>
          </div>
        </div>
      </div>
    </div>

    <router-view />
    <v-footer />
  </div>
</template>

<script>
import myFooter from '@/components/student/myFooter'
import { mapState } from 'vuex'
import 'element-ui/lib/theme-chalk/index.css'

export default {
  components: {
    'v-footer': myFooter
  },
  data() {
    return {
      flag: false,
      user: {},
      courseId: null,
      chatList: [],
      currentChatId: null,
      chatLog: [],
      inputContent: '',
      sending: false // 发送锁，防止重复点击
    }
  },
  created() {
    this.userInfo().then(() => {
      this.courseId = this.$route.params.courseId
      this.loadChatList()
    })
  },
  methods: {
    async userInfo() {
      const name = this.$cookies.get('cname')
      const id = this.$cookies.get('cid')
      this.user = { userName: name, studentId: id }
      return Promise.resolve()
    },
    async loadChatList() {
      const res = await this.$axios.get('/api/chat/chatlist', {
        params: {
          studentID: this.user.studentId,
          courseID: this.courseId
        }
      })
      if (res.data.code === 200) {
        this.chatList = res.data.data
        // If there are chats, load the most recent one if no chat is currently selected
        if (this.chatList.length > 0 && !this.currentChatId) {
          this.loadChat(this.chatList[0].chatID);
        }
      }
    },
    async startNewChat() {
      const res = await this.$axios.get('/api/chat/newchatid', {
        params: {
          studentID: this.user.studentId,
          courseID: this.courseId
        }
      })
      if (res.data.code === 200) {
        const newChatId = res.data.data
        this.currentChatId = newChatId
        this.chatLog = []
        this.inputContent = '' // Clear input for new chat
        this.loadChatList() // Reload chat list to show the new chat
      }
    },
    async loadChat(chatID) {
      this.currentChatId = chatID
      const res = await this.$axios.get('/api/chat/chatlog', {
        params: {
          studentID: this.user.studentId,
          courseID: this.courseId,
          chatID
        }
      })
      if (res.data.code === 200) {
        this.chatLog = res.data.data
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const chatLogEl = this.$el.querySelector('.chat-log')
        if (chatLogEl) {
          chatLogEl.scrollTop = chatLogEl.scrollHeight
        }
      })
    },
    async sendMessage() {
  if (!this.inputContent.trim() || !this.currentChatId || this.sending) return
  this.sending = true

  const userMessageContent = this.inputContent
  this.chatLog = [...this.chatLog, { speaker: 1, content: userMessageContent }]
  this.inputContent = ''
  this.$nextTick(() => this.scrollToBottom())

  const studentID = this.user.studentId
  const courseID = this.courseId
  const chatID = this.currentChatId

  let aiReply = ''
  this.chatLog = [...this.chatLog, { speaker: 2, content: aiReply }]
  this.$nextTick(() => this.scrollToBottom())

  try {
    // 拼接 SSE 接口 URL
    const query = new URLSearchParams({
      courseID,
      studentID,
      chatID,
      content: userMessageContent
    }).toString()

    const eventSource = new EventSource(`/api/chat/query?${query}`)

    eventSource.onmessage = (event) => {
  let incoming = event.data

  // 插入英文单词间的空格（仅英文时）
  if (
    /^[a-zA-Z]+$/.test(incoming) &&
    /\S$/.test(aiReply) &&
    /[a-zA-Z]$/.test(aiReply)
  ) {
    incoming = ' ' + incoming
  }

  aiReply += incoming

  const updated = [...this.chatLog]
  updated[updated.length - 1].content = aiReply
  this.chatLog = updated

  this.$nextTick(() => this.scrollToBottom())
}

    eventSource.onerror = () => {
      eventSource.close()
      this.sending = false
      if (!aiReply) {
        this.chatLog = this.chatLog.slice(0, -1)
        this.$message.error('AI 回复失败')
      }
      this.loadChatList()
    }

    // 若后端发送了一个事件 done 表示完成（可选）
    eventSource.addEventListener('done', () => {
      eventSource.close()
      this.sending = false

      // 更新历史记录预览
      const idx = this.chatList.findIndex(chat => chat.chatID === this.currentChatId)
      if (idx !== -1) this.chatList[idx].content = aiReply

      this.loadChatList()
    })
  } catch (e) {
    this.sending = false
    this.chatLog = this.chatLog.slice(0, -1)
    this.$message.error('连接失败')
  }
},
    async deleteChat(chatID) {
      this.$confirm('确定要删除该对话记录吗？', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$axios.delete('/api/chat/delete', {
          params: {
            courseID: this.courseId,
            studentID: this.user.studentId,
            chatID
          }
        })
        if (chatID === this.currentChatId) {
          this.currentChatId = null
          this.chatLog = []
        }
        this.loadChatList() // Still load chat list here to reflect deletion
        this.$message.success('删除成功')
      }).catch(() => {
        // User canceled
      })
    },
    manage() {
      this.$router.push('/student/manage');
    },
    exit() {
      this.$cookies.remove('cname');
      this.$cookies.remove('cid');
      this.$router.push('/login');
    }
  },
  computed: mapState(['isPractice'])
}
</script>

<style scoped>
/* Main container and header styles */
#student .padding-50 {
  margin: 0 auto;
  padding: 0 50px;
  box-shadow: 0 0 10px 4px rgba(1, 149, 255, 0.1);
  background-color: #fff;
}

.list {
  display: flex;
}

.list li {
  list-style: none;
  height: 60px;
  line-height: 60px;
  padding: 0 20px;
  cursor: pointer;
}

.list li:hover {
  background-color: #0195ff;
  transition: all 0.3s ease;
}

.list li:hover a {
  color: #fff;
}

.list a {
  text-decoration: none;
  color: #334046;
}

.list .right {
  margin-left: auto;
  position: relative;
}

.list li.right:hover a {
  color: #000;
}

.list .logo {
  display: flex;
  font-weight: bold;
  color: #2f6c9f;
}

.list .logo i {
  font-size: 50px;
}

.right .icon {
  margin-right: 6px;
}

.right .msg {
  text-align: center;
  position: absolute;
  top: 60px;
  right: 0;
  display: flex;
  flex-direction: column;
  border-radius: 2px;
  border-bottom: 3px solid #0195ff;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.right .msg p {
  height: 40px;
  line-height: 40px;
  width: 105px;
}

.right .msg p:hover {
  background-color: #0195ff;
  color: #fff;
}

/* Main chat area styles */
.main {
  padding: 20px 50px;
  background-color: #f9f9f9;
  min-height: 500px;
}

.chat-container {
  display: flex;
  height: 650px; /* Increased height for the entire chat container */
  border: 1px solid #e4e4e4;
  background: #fff;
}

/* Chat sidebar styles */
.chat-sidebar {
  width: 250px;
  border-right: 1px solid #ccc;
  padding: 10px;
  box-sizing: border-box;
  background: #f6f8fa;
  overflow-y: auto;
  height: 100%; /* Ensure sidebar takes full height of chat-container */
}

.chat-history {
  list-style: none;
  padding: 0;
  margin-top: 10px;
  max-height: calc(100% - 50px); /* Adjusted to accommodate the "New Chat" button */
  overflow-y: auto;
}

.chat-history li {
  padding: 12px 8px;
  min-height: 50px;
  line-height: 1.4;
  font-size: 15px;
  border-bottom: 1px solid #ddd;
  cursor: pointer;
  position: relative;
  white-space: normal;
  word-break: break-word;
  background-color: #fff;
  transition: background-color 0.3s;
}

.chat-history li.active {
  background: #dbeeff;
  font-weight: bold;
}

.chat-history li:hover {
  background-color: #ecf5ff;
}

.chat-history i {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  font-size: 18px;
  cursor: pointer;
}

/* Chat main window styles */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}

.chat-log {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.chat-empty {
  padding: 30px;
  color: #888;
  text-align: center;
}

/* Chat message bubble styles */
.chat-user {
  display: flex;
  justify-content: flex-end; /* 靠右 */
  margin-bottom: 10px;
}

.chat-ai {
  display: flex;
  justify-content: flex-start; /* 靠左 */
  margin-bottom: 10px;
}
.chat-content {
  display: block; /* block 元素会自动换行 */
  max-width: 70%;
  padding: 10px;
  border-radius: 10px;
  word-break: break-word; /* 允许单词在任何位置换行 */
  white-space: pre-wrap;  /* 保留空格和换行，同时支持自动换行 */
  line-height: 1.6;
}

.chat-user .chat-content {
  background: #cdefff; /* Blue for user messages */
}

.chat-ai .chat-content {
  background: #e7e7e7; /* Light gray for AI messages */
}

/* Chat input styles */
.chat-input {
  padding: 10px;
  border-top: 1px solid #ccc;
  display: flex;
  width: 100%;
  gap: 10px;
}
</style>